package com.example.controller;


import com.example.bean.Admin;
import com.example.bean.ApiResult;
import com.example.service.AdminService;
import com.example.utils.ApiResultHandler;
import com.example.utils.Md5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;


@RestController
@RequestMapping("/admin")
@CrossOrigin
public class AdminController {

    @Autowired
    private AdminService adminService;

    @GetMapping("/selectById/{adminId}")
    public ApiResult selectAdminById(@PathVariable String adminId){
        Admin res = adminService.selectAdminById(adminId);
        if(res!=null) return ApiResultHandler.buildApiResult(200,"根据管理员id查询",res);
        return ApiResultHandler.buildApiResult(400,"无此管理员信息",res);
    }

    @GetMapping("/selectAll")
    public ApiResult selectAdminAll(){
        List<Admin> res = adminService.selectAdminAll();
        if (res!=null) return ApiResultHandler.buildApiResult(200,"查询所有管理员",res);
        return ApiResultHandler.buildApiResult(400,"无此管理员信息",res);
    }

    @PostMapping("/insert")
    public ApiResult insertAdmin(@RequestBody Admin admin){
        String password = admin.getAdminPassword();
        password = Md5.md5(password);   //加密
        admin.setAdminPassword(password);
        int res = adminService.insertAdmin(admin);
        if(res!=0)  return ApiResultHandler.buildApiResult(200,"添加管理员成功",res);
        return ApiResultHandler.buildApiResult(400,"添加管理员失败",res);
    }

    @DeleteMapping("/delete/{adminId}")
    public ApiResult deleteAdmin(@PathVariable String adminId){
        int res = adminService.deleteAdmin(adminId);
        if (res!=0)  return ApiResultHandler.buildApiResult(200,"删除管理员成功",res);
        return ApiResultHandler.buildApiResult(400,"删除管理员失败",res);
    }

    @PutMapping("/update")
    public ApiResult updateAdmin(@RequestBody Admin admin){
        String password = admin.getAdminPassword();
        password = Md5.md5(password);   //加密
        admin.setAdminPassword(password);
        int res = adminService.updateAdmin(admin);
        if(res!=0)  return ApiResultHandler.buildApiResult(200,"更新管理员信息成功",res);
        return ApiResultHandler.buildApiResult(400,"更新管理员信息失败",res);
    }


}
